import { createSlice } from '@reduxjs/toolkit';
import type { PayloadAction } from '@reduxjs/toolkit';

export interface DanmuItem {
  id: number;
  text: string;
  color?: string;
  fontSize?: number;
  opacity?: number;
  shadow?: boolean;
  bold?: boolean;
  italic?: boolean;
  stroke?: boolean;
  style?: string;
  timestamp?: number; // 弹幕发送时的视频时间（秒）
}

interface DanmuState {
  list: DanmuItem[];
}

// 从 localStorage 读取历史弹幕
const getInitialDanmu = (): DanmuItem[] => {
  const saved = localStorage.getItem('danmu-list');
  return saved ? JSON.parse(saved) : [];
};

const initialState: DanmuState = {
  list: getInitialDanmu(),
};

const danmuSlice = createSlice({
  name: 'danmu',
  initialState,
  reducers: {
    addDanmu(state, action: PayloadAction<DanmuItem>) {
      state.list.push(action.payload);
      // 保存到 localStorage
      localStorage.setItem('danmu-list', JSON.stringify(state.list));
    },
    resetDanmu: (state) => {
      state.list = [];
      localStorage.setItem('danmu-list', '[]');
    },
  },
});

export const { addDanmu, resetDanmu } = danmuSlice.actions;
export default danmuSlice.reducer; 